package com.sky.d_lock_free;

import java.util.concurrent.atomic.AtomicReference;

/**
 * 测试AtomicReference封装String
 * @Author:hjt
 */
public class AtomicReferenceDemo {

	public final static AtomicReference<String> atomicString = new AtomicReference<>("apple");
	
	public static void main(String[] args) {
		for(int i=0;i<10;i++){
			new Thread(){
				public void run() {
					try {
						Thread.sleep((long)Math.abs(Math.random() * 100));
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
					String expect = "apple";
					String update = "banana";
					if(atomicString.compareAndSet(expect, update)){
						System.out.println(Thread.currentThread().getId() + " Change value");
					} else {
						System.out.println(Thread.currentThread().getId() + " Failed");
					}
				};
			}.start();
		}
		//运行结果表明只有一个线程可以修改值，后面的线程都不能再做修改
	}
}
